/**
 * 
 */
package com.istock.union.user.service.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.istock.base.serializer.json.TypeReference;
import com.istock.union.user.service.StorageService;

/**使用session作为内部存储机制
 * 需要在web.xml中配置
 * 
 * 需要配置XssSqlFilter,这个filter可以缓存request和response
 *  
 * @author senvon
 *
 */
public class SessionStorageService implements StorageService {

	
	@Override
	public void putObject(String token , String key, Object object) {
		putObject(token , key , object , null);
		
	}
	
	@Override
	public void putObject(String token, String key, Object object, Long expireSecond) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		HttpSession session = request.getSession(true);
		session.setAttribute(key, object);
	}

	@Override
	public <T> T getObject(String token , String key , TypeReference<T> type) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		if(request == null) {
			return null;
		}
		HttpSession session = request.getSession(true);
		if(session == null) {
			return null;
		}
		return (T)session.getAttribute(key);
	}

	@Override
	public void removeObject(String token, String key) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		if(request == null) {
			return ;
		}
		HttpSession session = request.getSession(true);
		if(session == null) {
			return ;
		}
		session.removeAttribute(key);
	}

	@Override
	public void removeAll(String token) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		if(request == null) {
			return ;
		}
		HttpSession session = request.getSession(true);
		if(session == null) {
			return ;
		}
		session.invalidate();
	}

}
